<template>
  <!-- v-for渲染菜单数据 -->
  <template v-for="(item, index) in filteredMenu" style="border-right: 3px">
    <!-- 若当前item没有children元素，或其长度为0，说明没有子菜单 -->
    <el-menu-item @click="handleClick(item, `${props.index}-${item.meta.id}`)"
                  v-if="!item.children || item.children.length == 0" :index="`${props.index}-${item.meta.id}`"
                  :key="`${props.index}-${item.meta.id}`">
      <el-icon size="20">
        <component :is="item.meta.icon"></component>
      </el-icon>
      <span>{{ item.meta.name }}</span>
    </el-menu-item>

    <!-- 有子菜单的情况，递归渲染 -->
    <el-sub-menu v-else :index="`${props.index}-${item.meta.id}`">
      <!-- 父菜单层渲染 -->
      <template #title>
        <el-icon size="20">
          <component :is="item.meta.icon"></component>
        </el-icon>
        <span>{{ item.meta.name }}</span>
      </template>
      <tree-menu :index="`${props.index}-${item.meta.id}`" :menuData="item.children" />
    </el-sub-menu>
  </template>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { checkPermission } from "@/composables/util.js";
import { computed } from "vue";
// 获取父组件传过来的数据
const props = defineProps(['menuData', 'index'])
const router = useRouter()
// 获取用户角色
const role = JSON.parse(localStorage.getItem("userInfo")).role
console.log("treeMenu获取角色："+role)
// 点击菜单时调用方法
const handleClick = (item, active) => {
  // 路由跳转
  router.push(item.meta.path)
}
// 递归过滤函数
const filterMenu = (menuList) => {
  return menuList.filter(item => {
    const hasPermission = checkPermission(item.meta?.roles, role)
    if (item.children) {
      item.children = filterMenu(item.children)
      // 子菜单全部过滤后，父菜单也应移除
      return hasPermission && item.children.length > 0
    }
    return hasPermission
  })
}

// 计算属性生成过滤后的菜单
const filteredMenu = computed(() => filterMenu(props.menuData))
console.log(filteredMenu)
</script>

<style lang="less" scoped>

</style>